<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\WorkEmployee\Action\Dashboard;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\User\Contract\UserContract;
use MoChat\App\WorkEmployee\Contract\WorkEmployeeContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 员工管理- 重置手机号.
 *
 * Class MobileReset.
 * @Controller
 */
class MobileReset extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var UserContract
     */
    protected $userService;

    /**
     * @Inject
     * @var WorkEmployeeContract
     */
    protected $workEmployeeService;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    private $logger;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/workEmployee/mobileReset", methods="put")
     * @return array 返回数组
     */
    public function index()
    {
        // 参数验证
        $this->validated($this->request->all());
        // 当前登录用户
        $user = user();
        // 接收参数
        $employeeId = $this->request->input('id');
        $mobile = $this->request->input('mobile');

        // 验证employeeId的有效性
        $employee = $this->workEmployeeService->getWorkEmployeeById((int) $employeeId, ['id', 'log_user_id', 'corp_id']);
        if (empty($employee)) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '当前员工不存在，不可操作');
        }

        $userId = $employee['logUserId'];
        if ($employee['corpId'] != $user['corpIds'][0]) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '当前员工您没有权限操作');
        }

        // 存在相同手机号则不能修改
        $userMobileInfo = $this->userService->getUserByPhone($mobile, ['id']);
        if (! empty($userMobileInfo) && $userMobileInfo['id'] != $userId) {
            //置空
            $this->userService->updateUserById((int) $userId, ['phone' => '']);
        }

        try {
            // 数据入库
            $this->workEmployeeService->updateWorkEmployeeById($employeeId, ['mobile' => $mobile]);
            $this->userService->updateUserById((int) $userId, ['phone' => $mobile]);
        } catch (\Throwable $e) {
            $this->logger->error(sprintf('%s [%s] %s', '账户更新手机号失败', date('Y-m-d H:i:s'), $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
            throw new CommonException(ErrorCode::SERVER_ERROR, '账户更新手机号失败');
        }
        return [];
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
            'id' => 'required|min:1',
            'mobile' => 'required',
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'id.required' => '员工id 必填',
            'mobile.required' => '手机号 必填',
        ];
    }
}
